package com.apes.framework.plugin.soe.store.database.service;


import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.core.utils.Const;
import com.apes.framework.plugin.soe.metadata.BusinessAction;
import com.apes.framework.plugin.soe.metadata.BusinessType;
import com.apes.framework.plugin.soe.store.database.repository.BusinessActionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("businessActionService")
public class BusinessActionService extends DomainService {

    @Autowired
    private Cache cache;

    @Autowired
    BusinessActionRepository businessActionRepository;


    /*
    * 创建
    * */
    public BusinessAction save(SimpleRequest simpleRequest) {
        BusinessAction businessAction = simpleRequest.getO(BusinessAction.class);
        return saveAndCache(businessAction);
    }

    public BusinessAction saveAndCache(BusinessAction businessAction) {
        BusinessAction other = getByCache(businessAction.getId());
        if (other != null && other.equals(businessAction)) return other;
        other = businessActionRepository.saveAndFlush(businessAction);
        cache.put(Const.CACHE_SCENE_BUSINESS_ACTION, other.getId(), other);
        return other;
    }

    public synchronized BusinessAction getByCache(String id) {
        BusinessAction businessAction = (BusinessAction) cache.get(Const.CACHE_SCENE_BUSINESS_ACTION, id);
        if (businessAction != null) return businessAction;
        businessActionRepository.findAll().stream().forEach(ba -> {
            cache.put(Const.CACHE_SCENE_BUSINESS_ACTION, ba.getId(), ba);
        });
        businessAction = (BusinessAction) cache.get(Const.CACHE_SCENE_BUSINESS_ACTION, id);
        return businessAction;
    }

    public String delete(SimpleRequest simpleRequest) {
        String id = simpleRequest.get("id");
        businessActionRepository.delete(id);
        return "删除成功!";
    }


}
